package com.gao.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author gaofeng
 * @date 2022年09月07日 19:36
 */
@Configuration
public class RabbitmqConfig {

    public static final String EXCHANGE_NAME = "boot_topic_exchange" ;
    public static final String QUEUE_NAME = "boot_topic_queue" ;
    public static final String ROUTING_KEY = "boot.#" ;
    public static final String ROUTING_KEY2 = "boot_confirm_key" ;
    public static final String ROUTING_KEY3 = "boot_dlx_key" ;

    /**
     * 1. 交换机
     */
    @Bean("bootExchange")
    public Exchange getExchange() {
//        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build() ;
        return ExchangeBuilder.directExchange(EXCHANGE_NAME).durable(true).build() ;
    }

    /**
     * a1. 死信交换机
     */
    @Bean("bootDlxExchange")
    public Exchange getDlxExchange() {
//        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build() ;
        return ExchangeBuilder.directExchange(EXCHANGE_NAME).durable(true).build() ;
    }

    /**
     * 2. 队列
     */
    @Bean("bootQueue")
    public Queue getQueue() {
//        return QueueBuilder.durable(QUEUE_NAME).build() ;
        // 给队列中的所有消息设置过期时间
        HashMap<String, Object> ttlTimeMap = new HashMap<>(1);
        // TTL+死信队列组合实现 延迟队列
        ttlTimeMap.put("x-message-ttl", 1000 * 60 * 30) ;
        // 正常队列绑定死信交换机
        ttlTimeMap.put("x-dead-letter-exchange", getDlxQueue()) ;
        ttlTimeMap.put("x-dead-letter-routing-key", ROUTING_KEY3) ;
        // 队列的长度限制
        ttlTimeMap.put("x-max-length", 10) ;
        return new Queue(QUEUE_NAME, false, false, false, ttlTimeMap) ;
    }

    /**
     * A2. 死信队列
     */
    @Bean("bootDlxQueue")
    public Queue getDlxQueue() {
//        return QueueBuilder.durable(QUEUE_NAME).build() ;
        // 给队列中的所有消息设置过期时间
        HashMap<String, Object> ttlTimeMap = new HashMap<>(1);
        ttlTimeMap.put("x-message-ttl", 3000) ;
        return new Queue(QUEUE_NAME, false, false, false, ttlTimeMap) ;
    }

    /**
     * 3. 交换机和队列绑定
     */
    @Bean
    public Binding bindQueueAndExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY2).noargs() ;
    }

    /**
     * a3. 死信交换机和死信队列绑定
     */
    @Bean
    public Binding bindDlxQueueAndExchange(@Qualifier("bootDlxQueue") Queue queue, @Qualifier("bootDlxExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY3).noargs() ;
    }


}
